package com.shelpe.service.simbaproxy;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.taobao.api.Constants;
import com.taobao.api.internal.util.StringUtils;

public class UtilsHelp {
    
	
	public static String listToString(List<?> list){
		
		if(list == null){
			return "";
		}
		
		StringBuilder result =  new StringBuilder();
		int size = list.size();
		for(int i = 0; i < size; i++){
			result.append(list.get(i).toString());
			if(i < size - 1){
				result.append(",");
			}
		}
		
		return result.toString();
	}
	

	public  static List<String> getDuplicateWord(List<String> wordList){
		
		Map<String, Integer> map = new HashMap<String, Integer>();
		for(String word : wordList){
			int value = 1;
			if(map.containsKey(word)){
				value = map.get(word) + value;
			}
			map.put(word, value);
		}
		//遍历map，返回重复的词列表
		List<String> res = new ArrayList<String>();
		for(Map.Entry<String, Integer> entry : map.entrySet()){
			
			if(entry.getValue() > 1){
				res.add(entry.getKey());
			}
		}
		
		return res;
	}
	
	public static List<String> filterDuplicateWord(List<String> wordList){
		
		Set<String> wordSet = new HashSet<String>();
		wordSet.addAll(wordList);
		
		List<String> res = new ArrayList<String>();
		res.addAll(wordSet);
		
		return res;
	}
	
	public static List<String> spiltKeyValueStr(String keyValueStr){
		
		String[] keyValues = keyValueStr.split(";");
		List<String> res = new ArrayList<String>();
		
		for(int i = 0; i < keyValues.length; i++){
			String[] keyValue = keyValues[i].split(":");
			if(keyValue.length == 4){
				String valueName = keyValue[3].replace("#cln#", ":");
				res.add(valueName.replace("scln#", ";"));
			}
		}
		
		return res;
	}
	
	
	public static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException, NoSuchAlgorithmException {
	    // 第一步：检查参数是否已经排序
	    String[] keys = params.keySet().toArray(new String[0]);
	    Arrays.sort(keys);
	 
	    // 第二步：把所有参数名和参数值串在一起
	    StringBuilder query = new StringBuilder();
	    if (Constants.SIGN_METHOD_MD5.equals(signMethod)) {
	        query.append(secret);
	    }
	    for (String key : keys) {
	        String value = params.get(key);
	        if (StringUtils.areNotEmpty(key, value)) {
	            query.append(key).append(value);
	        }
	    }
	 
	    // 第三步：使用MD5/HMAC加密
	    byte[] bytes;
	    if (Constants.SIGN_METHOD_HMAC.equals(signMethod)) {
	        bytes = encryptHMAC(query.toString(), secret);
	    } else {
	        query.append(secret);
	        bytes = encryptMD5(query.toString());
	    }
	 
	    // 第四步：把二进制转化为大写的十六进制
	    return byte2hex(bytes);
	}
	 
	public static byte[] encryptHMAC(String data, String secret) throws IOException {
	    byte[] bytes = null;
	    try {
	        SecretKey secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), "HmacMD5");
	        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
	        mac.init(secretKey);
	        bytes = mac.doFinal(data.getBytes(Constants.CHARSET_UTF8));
	    } catch (GeneralSecurityException gse) {
	        throw new IOException(gse.toString());
	    }
	    return bytes;
	}
	 
	public static byte[] encryptMD5(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException{
	    return encryptMD5(data.getBytes(Constants.CHARSET_UTF8));
	}
	 
	public static String byte2hex(byte[] bytes) {
	    StringBuilder sign = new StringBuilder();
	    for (int i = 0; i < bytes.length; i++) {
	        String hex = Integer.toHexString(bytes[i] & 0xFF);
	        if (hex.length() == 1) {
	            sign.append("0");
	        }
	        sign.append(hex.toUpperCase());
	    }
	    return sign.toString();
	}
	
	public static byte[] encryptMD5(byte[] data) throws NoSuchAlgorithmException{  
		  	
		MessageDigest md5 = MessageDigest.getInstance("MD5");    	 
		md5.update(data);  	  
		
		return md5.digest();   
	}  
	
}
